<?php

namespace Api\Controller;

use Common\Service\TraceService;
use Common\Service\AyduserService ;

class TraceController extends ApiController{
    
    function __construct() {
        parent::__construct();
    }
    
    function index(  ) {

        $p_code = I('param.p_code' );
        $a_code = I('param.a_code' );
        $sign   = I('param.sign' );
        
        $Trace = TraceService::instance();
        /*
        if ( !$Trace->valid_sign($p_code, $a_code, $sign) ) {
            return $this->ajaxReturn('签名验证失败');
        }
         * 
         */

        if( empty($p_code) && empty($a_code) && empty($sign) ) {
            //启动 
            $ipaddress = get_client_ip( 0 , TRUE);

            $p_code_data = $Trace->get_pcode_by_ip($ipaddress);
            print_r( $p_code );
            if ( empty( $p_code_data ) ) {
                echo 'Empty p_code_data 1';
                return ;
            }
            $p_code = $p_code_data['p_code'] ;
            $event = array_search( 'startup' , $Trace->event_text );
        } else {
            //注册
            if ( empty( $p_code ) && !empty( $a_code) ) {
                $ipaddress = get_client_ip(0, TRUE);
                $p_code_data = $Trace->get_pcode_by_ip($ipaddress);
                if ( empty( $p_code_data ) ) {
                    echo 'Empty p_code_data 2';
                    return ;
                }
                $p_code = $p_code_data['p_code'] ;
            }
            
            $event = array_search( 'reg' , $Trace->event_text );
        }
        
        //检查p_code是否合法
        $p_userid = 0 ;
        $User = AyduserService::instance();
        $p_code_data = $User->get_by_usercode($p_code) ;
        if ( empty($p_code_data) ) {
            echo 'Empty p_code_data 3';
            return ;
        }
        $p_userid = $p_code_data['id'] ;
        
        $a_userid = 0 ;
        if ( !empty( $a_code ) ) {
            //检查a_code是否合法
            
            $a_code_data = $User->get_by_usercode($a_code) ;
            if ( empty( $a_code_data ) ) {
                echo 'Empty a_code_data 1';
                return ;
            }
            $a_userid = $a_code_data['id'];
        }
        
        
        $ret = $Trace->add_trace( $event , $p_code , $p_userid , $a_code , $a_userid );
        
        $this->ajaxReturn($ret);
    }
    
}


